﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ajax;
using SeDuce.BLL;
using SeDuce.Model;
using System.Data.SqlClient;
using SeDuce.DAL;
using System.Data;

public partial class News : RepeaterPagerBase
{
    Lazy_Yu<BrandBLL> lazyBrandBLL = new Lazy_Yu<BrandBLL>(() => new BrandBLL());
    public BrandBLL LazyBrandBLL
    {
        get { return this.lazyBrandBLL.Value; }
    }

    Lazy_Yu<AdBLL> lazyAdBLL = new Lazy_Yu<AdBLL>(() => new AdBLL());
    public AdBLL LazyAdBLL
    {
        get { return this.lazyAdBLL.Value; }
    }

    Lazy_Yu<NewsBLL> lazyNewsBLL = new Lazy_Yu<NewsBLL>(() => new NewsBLL());
    public NewsBLL LazyNewsBLL
    {
        get { return this.lazyNewsBLL.Value; }
    }
    Lazy_Yu<NewsTypeBLL> lazyNewsTypeBLL = new Lazy_Yu<NewsTypeBLL>(() => new NewsTypeBLL());
    public NewsTypeBLL LazyNewsTypeBLL
    {
        get { return this.lazyNewsTypeBLL.Value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Ajax.Utility.RegisterTypeForAjax(typeof(News));
        BindCategories();
        if (!IsPostBack)
        {
            this.rptAds.DataSource = this.LazyAdBLL.GetAds().ToList<Ad>().Where<Ad>(a => a.Enabled == true);
            this.rptAds.DataBind();
            this.rptNewsGallery.DataSource = this.LazyNewsBLL.GetNewsInGallery();
            this.rptNewsGallery.DataBind();

            List<SeDuce.Model.News> headlines = this.LazyNewsBLL.GetNewsIsHeadline(10).ToList<SeDuce.Model.News>();
            List<SeDuce.Model.News> imgs = headlines.Where(n => n.IsHeadline == 1).Select(n => n).ToList<SeDuce.Model.News>();
            for (int i = 0, len = 4-imgs.Count; i < len; i++)
            {
                imgs.Add(new SeDuce.Model.News());
            }
            this.rptHeadline.DataSource = headlines.Where(n => n.IsHeadline == 1).Select(n=>n);
            this.rptHeadline.DataBind();
            this.rptHeadline2.DataSource = headlines.Where(n => n.IsHeadline == 2).Select(n => n);
            this.rptHeadline2.DataBind();

            //首页跳转正文页
            if (this.GetQueryString("newsID", false) != null)
            {
                DataTable dtNews = LazyNewsBLL.GetNewsByID(this.GetQueryString("newsID", false).ToInt());
                if (dtNews.Rows.Count > 0)
                {
                    this.Panel1.Visible = false;
                    this.Panel2.Visible = true;
                    this.literTitle.Text = dtNews.Rows[0]["Title"].ToString();
                    this.imgPic.ImageUrl = this.ResolveUrl(dtNews.Rows[0]["Pic"].ToString());
                    this.literContent.Text = dtNews.Rows[0]["ContentText"].ToString();
                    this.AddAttributes("NewsType", dtNews.Rows[0]["TypeID"].ToString());
                }
            }
        }
        List<ArticleCategory> titles = new List<ArticleCategory>();
        List<SeDuce.Model.NewsType> newsTypes = this.LazyNewsTypeBLL.GetNewsType().ToList<SeDuce.Model.NewsType>();
        foreach (SeDuce.Model.NewsType t in newsTypes)
        {
            titles.Add(new ArticleCategory() { ID = t.ID, TitleText = t.TypeName });
        }
        this.Repeater1.DataSource = titles;
        this.Repeater1.DataBind();
        this.BindNewsList();
        this.RemoveAttributes("NewsType");
        
    }

    private void BindNewsList()
    {
        List<SqlParameter> sp = new List<SqlParameter>();
        string where = string.Empty;

        if (!string.IsNullOrEmpty(this.GetAttributes("Type_Filter")))
        {
            string key = this.GetAttributes("Type_Filter").Split('=')[0];
            string value = this.GetAttributes("Type_Filter").Split('=')[1];
            sp.Add(new SqlParameter("@" + key, value));
            where += string.Format(" AND TbNews.{0}=@{0}", key);
        }
        this.RegistrPager(this.rptNewsList, this.rptPageFliper, 7, this.FillPageMoudleWithParams(PageSize, SeDuce.DAL.NewsDAL.sqlGetNews + where, sp.ToArray(), new List<SortField>() { 
            new SortField() { FieldName = "UpdateDate", DESC = true }
        }));

        
    }

    protected void rptCategories_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "CATEGORY_CHANGE")
        {
            LinkButton lbtnCategory = (LinkButton)e.Item.FindControl("lbtnCategory");
            Response.Redirect(ResolveUrl("~/Brands/" + e.CommandArgument.ToString()));
        }
    }

    protected void rptNewsList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "News_View")
        {
            LinkButton lbtnNews = (LinkButton)e.Item.FindControl("lbtnNews");
            DataTable dtNews = LazyNewsBLL.GetNewsByID(e.CommandArgument.ToString().ToInt());
            if (dtNews.Rows.Count > 0)
            {
                this.Panel1.Visible = false;
                this.Panel2.Visible = true;
                this.literTitle.Text = dtNews.Rows[0]["Title"].ToString();
                this.imgPic.ImageUrl = this.ResolveUrl(dtNews.Rows[0]["Pic"].ToString());
                this.literContent.Text = dtNews.Rows[0]["ContentText"].ToString();
            }
        }
    }

    private void BindCategories()
    {
        this.rptCategories.DataSource = this.LazyBrandBLL.GetBrands().ToList<Brand>().OrderBy(t => t.Sort).ToList<Brand>();
        this.rptCategories.DataBind();
    }

    [Ajax.AjaxMethod()]
    public bool UpdateBrands()
    {
        try
        {
            BindCategories();
            return true;
        }
        catch { return false; }
    }


    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Title_Change")
        {
            try
            {
                LinkButton lbtnTitle = (LinkButton)e.Item.FindControl("lbtnTitle");
                lbtnTitle.ForeColor = System.Drawing.Color.FromArgb(197, 147, 16);
                this.AddAttributes("Type_Filter", "TypeID=" + e.CommandArgument.ToString());
                this.Panel1.Visible = true;
                this.Panel2.Visible = false;
                this.BindNewsList();
                this.BindPage(this.rptPageFliper.UniqueID, 1);
            }
            catch { }
        }
    }
    protected void lbtnBack_Click(object sender, EventArgs e)
    {
        this.Panel1.Visible = true;
        this.Panel2.Visible = false;
    }
    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
        {
            LinkButton lbtnTitle = (LinkButton)e.Item.FindControl("lbtnTitle");
            if (this.GetAttributes("NewsType") == ((SeDuce.Model.ArticleCategory)e.Item.DataItem).ID.ToString())
            {
                lbtnTitle.ForeColor = System.Drawing.Color.FromArgb(197, 147, 16);
            }
            else
            {
                lbtnTitle.ForeColor = System.Drawing.Color.FromArgb(120, 120, 120);
            }
        }
    }

    protected string GetContent(RepeaterItem container, string type)
    {
        string html = string.Empty;
        switch (type)
        {
            case "IMAGE":
                if (container.DataItem != null)
                {
                    html = "<a href='" + ResolveUrl("~/News/" + Eval("ID").ToString()) + "' title='" + HttpUtility.HtmlEncode(Eval("Title").ToString()) + "' class=\"tc\"><img alt='" + HttpUtility.HtmlEncode(Eval("Title").ToString()) + "' src='" + ResolveUrl(Eval("Pic").ToString()) + "' border=\"0\" width=\"204\" height=\"136\" /></a>";
                }
                else
                {
                    html = "<a></a>";
                }
                break;
            case "TEXT":
                html = "<a href='" + ResolveUrl("~/News/" + Eval("ID").ToString()) + "' title='" + HttpUtility.HtmlEncode(Eval("Title").ToString()) + "' class=\"tc\"><span>" + HttpUtility.HtmlEncode(Eval("Title").ToString()) + "</span></a>";
                break;
            default:
                break;
        }
        return html;

        //if ((container.ItemIndex + 1) <= 4)
        //{
        //    return "<img alt='" + HttpUtility.HtmlEncode(Eval("Title").ToString()) + "' src='" + ResolveUrl(Eval("Pic").ToString()) + "' border=\"0\" width=\"204\" height=\"136\" />";
        //}
        //else
        //{
        //    return "<span>"+HttpUtility.HtmlEncode(Eval("Title").ToString())+"</span>";
        //}
    }


    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        int num = 0;
        if (int.TryParse(this.txtPageNum.Text.Trim(), out num))
        {
            if (num <= this.TotalPage(this.rptPageFliper.UniqueID) && num > 0)
            {
                this.BindNewsList();
                this.BindPage(this.rptPageFliper.UniqueID, num);
            }
        }
    }
}